package com.visionork.android.twe.activity;

import java.util.ArrayList;
import java.util.List;

import com.visionork.android.twe.parser.ShowAdapter;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public abstract class ShowListActivityBase extends ListActivity {
	private class LoadShowTask extends AsyncTask<Void, Void, Void> {
		protected ProgressDialog _pd;
		@Override
		protected Void doInBackground(Void... params) {
			try {
				_show_list = get_show_adapter().get_show_list();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			_pd = ProgressDialog.show(ShowListActivityBase.this, "加载中...",
					"读取节目列表", true, false);
		}

		@Override
		protected void onPostExecute(Void param) {
			List<String> titles = new ArrayList<String>(_show_list.size());

			for (Show show : _show_list) {
				titles.add(show.get_title());
			}

			setListAdapter(new ArrayAdapter<String>(ShowListActivityBase.this,
					R.layout.show_list_item, titles));
			_pd.dismiss();
		}
	}

	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_list);
		load_shows();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Show show = _show_list.get(position);
		Intent intent = new Intent(this, ShowScheduleActivity.class);
		intent.putExtra(ShowScheduleActivity.SCHEDULE_TITLE, show.get_title());
		intent.putExtra(ShowScheduleActivity.SCHEDULE_URL, show.get_url());
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.show_list_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected (MenuItem item) {
		switch (item.getItemId()) {
		case R.id.refresh:
			load_shows();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void load_shows() {
		LoadShowTask task = new LoadShowTask();
		task.execute(new Void[] {});
	}

	protected abstract ShowAdapter get_show_adapter();

	private ArrayList<Show> _show_list;
}
